package com.example.javaproject.thread.productandconsumer;

/**
 * Description: 生产者消费者模式，过早通知的问题,文献地址 https://www.jianshu.com/p/e29632593057
 * <br>Author：tian
 * <br>Time: 2019/2/28 16:20
 *
 * @see <a href="https://www.jianshu.com/p/e29632593057">通知过早</a>
 */
public class EarlyNotify {

    private static String lock = "";
    private static volatile boolean isWait = true;

    public static void main(String[] args) {
        EarlyNotify e = new EarlyNotify();
        e.test(lock);
    }

    private void test(String lock) {
        Producer producter = new Producer(lock);
        Consumer consumer = new Consumer(lock);
        producter.start();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        consumer.start();
    }

    class Producer extends Thread {
        private String mLock;

        public Producer(String mLock) {
            this.mLock = mLock;
            setName("producter-thead");
        }

        @Override
        public void run() {
            synchronized (mLock) {
                System.out.println(Thread.currentThread().getName() + " 开始执行");
                System.out.println(Thread.currentThread().getName() + " 开始notify");
                mLock.notify();
                //修正过早的通知,测试的时候写注掉在打开
                isWait = false;
                System.out.println(Thread.currentThread().getName() + " 结束notify");
            }
        }
    }

    class Consumer extends Thread {
        private final String mLock;

        public Consumer(String mLock) {
            this.mLock = mLock;
            setName("consumer-thread");
        }

        @Override
        public void run() {
            synchronized (mLock) {
                try {
                    System.out.println(Thread.currentThread().getName() + " 开始执行");
                    System.out.println(Thread.currentThread().getName() + " 开始wait");
                    while (isWait) {
                        mLock.wait();
                    }
                    System.out.println(Thread.currentThread().getName() + " 结束wait");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}


